package com.core.MQ;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@Profile("mq-rocket") // 关键：只有当 "mq-rocket" profile 激活时，这个Bean才会被创建
@RequiredArgsConstructor
public class RocketMQProducerImpl implements MessageProducer {

    private final RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendMessage(String topic, Object payload) {
        // 1.改造topic，将 topic 参数构造成 topic:tag 的形式。比如，业务层调用 sendMessage("reservation.success", ...)
        // 假设 topic 的格式是 "mainTopic.tag"
        String[] parts = topic.split("\\.", 2);
        String destination = topic;
        if (parts.length == 2) {
            // e.g., "reservation.success" -> "reservation_topic:success"
            // 实际的 Topic 名称最好从配置读取
            destination = "RESERVATION_TOPIC:" + parts[1];
        }
        log.info("使用 RocketMQ 发送消息. Topic: {}, Payload: {}", destination, payload);
        // 2.发送消息
        try {
            // 在RocketMQ中，"topic" 参数可以直接用作 destination (格式通常是 "topicName:tagName")
            rocketMQTemplate.convertAndSend(destination, payload);
        } catch (Exception e) {
            log.error("RocketMQ 消息发送失败. Topic: {}, Payload: {}", destination, payload, e);
        }
    }
}